package com.xiyoufang.club.tio;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiyoufang.club.response.JMessageProtocalRes;
import com.xiyoufang.club.service.IClubService;
import com.xiyoufang.club.service.TioUtil;
import com.xiyoufang.club.service.impl.ClubServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.server.handler.IWsMsgHandler;

@Component
public class MyWebSocketMsgHandler implements IWsMsgHandler {

    @Autowired
//    @Qualifier(value="ClubServiceImpl")
    private IClubService clubServiceImpl;

    @Autowired
    private TioUtil tioUtil;

    @Override
    public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        return httpResponse;
    }

    @Override
    public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        System.out.println("握手成功");
    }

    @Override
    public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        System.out.println("接收到bytes消息");
        return null;
    }

    @Override
    public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        return null;
    }

    @Override
    public Object onText(WsRequest wsRequest, String s, ChannelContext channelContext) throws Exception {
        System.out.println(s);
        JSONObject json = JSON.parseObject(s);
        JMessageProtocalRes club = null;
        switch (json.getInteger("subType")) {
            case 1:
                club = clubServiceImpl.findClub(s);
                break;
            case 2:
                club = clubServiceImpl.createClub(s);
                break;

            case 11:
                clubServiceImpl.clubRoomInfo(s);
            default:

        }
        tioUtil.pushMessage(JSON.toJSONString(club));
        System.out.println("发送消息：" + JSON.toJSONString(club));
        return null;
    }
}